package com.chinadaas.hangzhou.archetypeweb.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class ElasticConfig {

    @Value("${elasticsearch.username:#{null}}")
    private String username;

    @Value("${elasticsearch.password:#{null}}")
    private String password;

    @Bean
    RestHighLevelClient restHighLevelClient(@Value("${elasticsearch.cluster-nodes}") String clusterNodes) {

        final CredentialsProvider provider = new BasicCredentialsProvider();
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        }

        String[] hostAndPort = clusterNodes.split(",", -1);
        HttpHost[] httpHosts = new HttpHost[hostAndPort.length];
        for (int i = 0; i < hostAndPort.length; i++) {
            String[] arr = hostAndPort[i].split(":", -1);
            httpHosts[i] = new HttpHost(arr[0], Integer.parseInt(arr[1]));
        }
        RestClientBuilder builder = RestClient.builder(httpHosts)
                .setHttpClientConfigCallback(
                        httpClientBuilder -> {
                            httpClientBuilder.setMaxConnPerRoute(100);
                            httpClientBuilder.setMaxConnTotal(300);
                            httpClientBuilder.disableAuthCaching();
                            httpClientBuilder.setDefaultCredentialsProvider(provider);
                            return httpClientBuilder;
                        })
                .setRequestConfigCallback(requestConfigBuilder -> {
                    requestConfigBuilder.setConnectTimeout(5000);
                    requestConfigBuilder.setSocketTimeout(30000);
                    requestConfigBuilder.setConnectionRequestTimeout(2000);
                    return requestConfigBuilder;
                }).setMaxRetryTimeoutMillis(50 * 1000);
        // 创建高级客户端
        return new RestHighLevelClient(builder);
    }
}